package com.tjp.eight.ui.fragment.homepage;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.tjp.eight.R;
import com.tjp.eight.ResultModel;
import com.tjp.eight.comment.AppManager;
import com.tjp.eight.ui.fragment.BaseFragment;
import com.tjp.eight.utils.IsSuccessUtils;
import com.tjp.eight.utils.SharePreferencesUtils;
import com.tjp.eight.utils.StringUtils;
import com.tjp.eight.utils.ToatUtils;
import com.tjp.eight.views.CircleImageView;
import com.tjp.eight.views.DialogSendingComment;
import com.tjp.eight.views.LogoutDailog;
import com.tjp.eight.views.NoScrollViewPager;
import com.tjp.eight.views.rcview.EndlessRecyclerOnScrollListener;
import com.tjp.eight.views.rcview.HeaderViewRecyclerAdapter;
import com.tjp.eight.views.rcview.ItemRemoveRecyclerView;
import com.tjp.eight.views.rcview.OnItemClickListener;

import java.util.ArrayList;

/**
 * Created by Administrator on 2017/2/18.
 */

public class FragmentHomePage extends BaseFragment<HomePagePresenter> implements HomePageView {
    private TextView tvAction;
    private TextView tvComment;
    private TextView tvShare;
    private TextView tvCollection;
    private NoScrollViewPager noScrollViewPager;
    private AppBarLayout appbar;
    private RelativeLayout rl_alpha_bg;
    private RelativeLayout rl_back;
    private View actionView;
    private View commentView;
    private View shareView;
    private View collectionView;
    private HomePageAdapter actionApter;
    private HomePageAdapter commentAdapter;
    private HomePageAdapter shareAdapter;
    private HomePageAdapter collectionAdapter;
    private HeaderViewRecyclerAdapter actionHeader;
    private HeaderViewRecyclerAdapter commentHeader;
    private HeaderViewRecyclerAdapter shareHeader;
    private HeaderViewRecyclerAdapter collectionHeader;
    private RecyclerView rvContainerAction;
    private RecyclerView rvContainerComment;
    private RecyclerView rvContainerShare;
    private ItemRemoveRecyclerView rvContainerCollection;
    private ArrayList<View> viewArrayList;
    private View footView;
    private final int TYPE_ACTION = 1;
    private final int TYPE_COMMENT = 2;
    private final int TYPE_SHARE = 3;
    private final int TYPE_COLLECTION = 4;
    private TextView tv_user_name;
    private CircleImageView civ_home_pic_u;
    private int currentPos = -1;
    private DialogSendingComment sendingLoad;

    @Override
    protected HomePagePresenter createPresenter() {
        return new HomePagePresenter(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = super.onCreateView(inflater, container, savedInstanceState);
        if (contentView == null) {
            contentView = inflater.from(getContext()).inflate(R.layout.my_home_page, container, false);
        }
        initViews();
        return contentView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        presenter.loadAction(getPJson(TYPE_ACTION, 1));
        presenter.loadComment(getPJson(TYPE_COMMENT, 1));
        presenter.loadShare(getPJson(TYPE_SHARE, 1));
        presenter.loadCollection(getPJson(TYPE_COLLECTION, 1));
    }

    View.OnClickListener tabClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_action:
                    resetTabState();
                    tvAction.setSelected(true);
                    noScrollViewPager.setCurrentItem(0);
                    break;
                case R.id.tv_comment:
                    resetTabState();
                    tvComment.setSelected(true);
                    noScrollViewPager.setCurrentItem(1);
                    break;
                case R.id.tv_share:
                    resetTabState();
                    tvShare.setSelected(true);
                    noScrollViewPager.setCurrentItem(2);
                    break;
                case R.id.tv_collection:
                    resetTabState();
                    tvCollection.setSelected(true);
                    noScrollViewPager.setCurrentItem(3);
                    break;
            }
        }
    };

    void initViews() {
        tv_user_name = (TextView) contentView.findViewById(R.id.tv_user_name);
        civ_home_pic_u = (CircleImageView) contentView.findViewById(R.id.civ_home_pic_u);
        Glide.with(getContext()).load(SharePreferencesUtils.getUserUrl()).error(R.drawable.icon_login).into(civ_home_pic_u);
        tv_user_name.setText("" + SharePreferencesUtils.getName());
        appbar = (AppBarLayout) contentView.findViewById(R.id.appbar);
        rl_alpha_bg = (RelativeLayout) contentView.findViewById(R.id.rl_alpha_bg);
        rl_back = (RelativeLayout) contentView.findViewById(R.id.rl_back);

        appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                float offset = Math.abs(verticalOffset);
                float range = appbar.getTotalScrollRange();
                float alpha = offset / range;
                rl_alpha_bg.setAlpha(alpha);
            }
        });
        rl_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppManager.getAppManager().finishActivity(getActivity());
            }
        });

        tvAction = (TextView) contentView.findViewById(R.id.tv_action);
        tvComment = (TextView) contentView.findViewById(R.id.tv_comment);
        tvShare = (TextView) contentView.findViewById(R.id.tv_share);
        tvCollection = (TextView) contentView.findViewById(R.id.tv_collection);

        tvAction.setOnClickListener(tabClick);
        tvComment.setOnClickListener(tabClick);
        tvShare.setOnClickListener(tabClick);
        tvCollection.setOnClickListener(tabClick);

        noScrollViewPager = (NoScrollViewPager) contentView.findViewById(R.id.nvp_my_home);
        noScrollViewPager.setNoScroll(true);
        footView = LayoutInflater.from(getContext()).inflate(R.layout.swipe_refresh_footer, null, false);
        initTabViews();
    }

    void initTabViews() {
        actionView = LayoutInflater.from(getContext()).inflate(R.layout.item_container_my_page, null, false);
        commentView = LayoutInflater.from(getContext()).inflate(R.layout.item_container_my_page, null, false);
        shareView = LayoutInflater.from(getContext()).inflate(R.layout.item_container_my_page, null, false);
        collectionView = LayoutInflater.from(getContext()).inflate(R.layout.item_re_container_my_page, null, false);

        rvContainerAction = (RecyclerView) actionView.findViewById(R.id.rv_container_my_page);
        rvContainerComment = (RecyclerView) commentView.findViewById(R.id.rv_container_my_page);
        rvContainerShare = (RecyclerView) shareView.findViewById(R.id.rv_container_my_page);
        rvContainerCollection = (ItemRemoveRecyclerView) collectionView.findViewById(R.id.rv_container_my_page);


        viewArrayList = new ArrayList<>();
        viewArrayList.add(actionView);
        viewArrayList.add(commentView);
        viewArrayList.add(shareView);
        viewArrayList.add(collectionView);


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        LinearLayoutManager linearLayoutManager3 = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        rvContainerAction.setLayoutManager(linearLayoutManager);
        rvContainerComment.setLayoutManager(linearLayoutManager1);
        rvContainerShare.setLayoutManager(linearLayoutManager2);
        rvContainerCollection.setLayoutManager(linearLayoutManager3);

        actionApter = new HomePageAdapter(getContext());
        commentAdapter = new HomePageAdapter(getContext());
        shareAdapter = new HomePageAdapter(getContext());
        collectionAdapter = new HomePageAdapter(getContext());
        actionHeader = new HeaderViewRecyclerAdapter(actionApter);
        commentHeader = new HeaderViewRecyclerAdapter(commentAdapter);
        shareHeader = new HeaderViewRecyclerAdapter(shareAdapter);
        collectionHeader = new HeaderViewRecyclerAdapter(collectionAdapter);
        actionHeader.addFooterView(footView);
        commentHeader.addFooterView(footView);
        shareHeader.addFooterView(footView);
        collectionHeader.addFooterView(footView);

        rvContainerAction.setAdapter(actionApter);
        rvContainerComment.setAdapter(commentAdapter);
        rvContainerShare.setAdapter(shareAdapter);

        collectionAdapter.setCanClick(false);
        rvContainerCollection.setAdapter(collectionAdapter);
        rvContainerCollection.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                collectionAdapter.startDetails(position);
            }

            @Override
            public void onDeleteClick(int position) {
                collectionAdapter.removeItem(position);
            }
        });
        collectionAdapter.setUnCollection(new HomePageAdapter.UnCollection() {
            @Override
            public void unCollection(String contentId, String type, int position) {
                showLoading();
                //collectionAdapter.reMoveItemSuccess(position);
                currentPos = position;
                presenter.unCollection(getPUJson(contentId, type));
            }
        });

        rvContainerAction.addOnScrollListener(new EndlessRecyclerOnScrollListener(linearLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
                presenter.loadAction(getPJson(TYPE_ACTION, currentPage));
            }
        });
        rvContainerComment.addOnScrollListener(new EndlessRecyclerOnScrollListener(linearLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
                presenter.loadComment(getPJson(TYPE_COMMENT, currentPage));
            }
        });
        rvContainerShare.addOnScrollListener(new EndlessRecyclerOnScrollListener(linearLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
                presenter.loadShare(getPJson(TYPE_SHARE, currentPage));
            }
        });
        rvContainerCollection.addOnScrollListener(new EndlessRecyclerOnScrollListener(linearLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
                presenter.loadCollection(getPJson(TYPE_COLLECTION, currentPage));
            }
        });

        noScrollViewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return viewArrayList.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(viewArrayList.get(position));
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(viewArrayList.get(position));
                return viewArrayList.get(position);
            }
        });
        tvAction.setSelected(true);
        int item = getActivity().getIntent().getIntExtra("item", 1);
        toItem(item);

    }

    private String getPUJson(String contentId, String type) {
        UnCollectionPModel model = new UnCollectionPModel();

        model.cid = contentId;
        model.type = type;
        model.uid = SharePreferencesUtils.getUid();
        model.loginkey = SharePreferencesUtils.getLoginKey();
        return new Gson().toJson(model);
    }

    void toItem(int item) {
        switch (item) {
            case 1:
                resetTabState();
                tvAction.setSelected(true);
                noScrollViewPager.setCurrentItem(0);
                break;
            case 2:
                resetTabState();
                tvComment.setSelected(true);
                noScrollViewPager.setCurrentItem(1);
                break;
            case 3:
                resetTabState();
                tvShare.setSelected(true);
                noScrollViewPager.setCurrentItem(2);
                break;
            case 4:
                resetTabState();
                tvCollection.setSelected(true);
                noScrollViewPager.setCurrentItem(3);
                break;
        }
    }

    private void showLoading() {
        if (sendingLoad == null) {
            sendingLoad = new DialogSendingComment(getContext());
        }
        sendingLoad.show();
    }

    private void hideLoading() {
        if (sendingLoad != null) {
            sendingLoad.dismiss();
        }
    }

    void resetTabState() {
        tvAction.setSelected(false);
        tvComment.setSelected(false);
        tvShare.setSelected(false);
        tvCollection.setSelected(false);
    }

    private String getPJson(int type, int page) {
        HomePModel model = new HomePModel();
        model.type = type;
        model.page = page;
        model.uid = SharePreferencesUtils.getUid();
        model.loginkey = SharePreferencesUtils.getLoginKey();
        return new Gson().toJson(model);
    }

    @Override
    public void loadActionSuccess(HomeRModel model) {
        if (model == null || model.data.listdata == null) {
            actionHeader.removeFootByIndex(0);
            return;
        }
        tvAction.setText("" + StringUtils.toWan(model.total_items));
        if (IsSuccessUtils.isSuccess(model.result)) {
            actionApter.addData(model.data.listdata);
            if (actionApter.getItemCount() >= model.total_items) {
                actionHeader.removeFootByIndex(0);
            } else {
                if (actionHeader.getFooterCount() == 0) {
                    actionHeader.addFooterView(footView);
                }
            }
        } else {
            ToatUtils.toastSuccess(getContext(), model.msg);
        }
    }

    @Override
    public void loadFail(String msg) {
        hideLoading();
    }

    @Override
    public void loadCommentSuccess(HomeRModel model) {
        if (model == null || model.data.listdata == null) {
            commentHeader.removeFootByIndex(0);
            return;
        }
        tvComment.setText("" + StringUtils.toWan(model.total_items));
        if (IsSuccessUtils.isSuccess(model.result)) {
            commentAdapter.addData(model.data.listdata);
            if (commentAdapter.getItemCount() >= model.total_items) {
                commentHeader.removeFootByIndex(0);
            } else {
                if (commentHeader.getFooterCount() == 0) {
                    commentHeader.addFooterView(footView);
                }
            }
        } else {
            ToatUtils.toastSuccess(getContext(), model.msg);
        }
    }

    @Override
    public void loadShareSuccess(HomeRModel model) {
        if (model == null || model.data.listdata == null) {
            shareHeader.removeFootByIndex(0);
            return;
        }
        tvShare.setText("" + StringUtils.toWan(model.total_items));
        if (IsSuccessUtils.isSuccess(model.result)) {
            shareAdapter.addData(model.data.listdata);
            if (shareAdapter.getItemCount() >= model.total_items) {
                shareHeader.removeFootByIndex(0);
            } else {
                if (shareHeader.getFooterCount() == 0) {
                    shareHeader.addFooterView(footView);
                }
            }
        } else {
            ToatUtils.toastSuccess(getContext(), model.msg);
        }
    }

    @Override
    public void loadCollectionSuccess(HomeRModel model) {
        if (model == null || model.data.listdata == null) {
            collectionHeader.removeFootByIndex(0);
            return;
        }
        tvCollection.setText("" + StringUtils.toWan(model.total_items));
        if (IsSuccessUtils.isSuccess(model.result)) {
            collectionAdapter.addData(model.data.listdata);
            if (collectionAdapter.getItemCount() >= model.total_items) {
                collectionHeader.removeFootByIndex(0);
            } else {
                if (collectionHeader.getFooterCount() == 0) {
                    collectionHeader.addFooterView(footView);
                }
            }
        } else {
            ToatUtils.toastSuccess(getContext(), model.msg);
        }
    }

    @Override
    public void unCollection(ResultModel model) {
        hideLoading();
        if (model != null) {
            if (IsSuccessUtils.isSuccess(model.result)) {
                ToatUtils.toastSuccess(getContext(), "取消收藏");
                collectionAdapter.reMoveItemSuccess(currentPos);
                tvCollection.setText("" + collectionAdapter.getItemCount());
                currentPos = -1;
            } else {
                ToatUtils.toastSuccess(getContext(), model.msg);
            }
        }
    }
}
